#!/bin/bash
set -xe

export SERVICE_NAME="server_common"
export DOCKER_REPO="docker.hongchow.com:8443/uniform"
# 需要压缩的文件选项（未编译docker）
export ZIP="src"
# 需要压缩的文件选项（编译docker）
export ZIP_COMPILE=""
# 是否需要清理空间
export NEED_CLEAN=no

createYaml(){
    ACTION=$1
    folder=tag
    if [[ $TAG = "" ]]; then
        folder=yaml
    fi

    sudo cp -f $WORKSPACE/devops/$folder/docker-compose.yaml $WORKSPACE/docker/$ACTION.yaml

    COMMAND=""

    # 根据命令修改脚本
    case $ACTION in
        "command_dispatch")
            COMMAND="php src/artisan uniform:command_dispatch"
            sudo sed -e "/port/d" -e "/PORT/d" -i $WORKSPACE/docker/$ACTION.yaml
        ;;
        "command_queue")
            COMMAND="php src/artisan uniform:swoole_queue --queue=command"
            sudo sed -e "/port/d" -e "/PORT/d" -i $WORKSPACE/docker/$ACTION.yaml
        ;;
        "api_queue")
            COMMAND="php src/artisan uniform:swoole_queue --queue=api"
            sudo sed -e "/port/d" -e "/PORT/d" -i $WORKSPACE/docker/$ACTION.yaml
        ;;
        "email_queue")
            COMMAND="php src/artisan uniform:swoole_queue --queue=email"
            sudo sed -e "/port/d" -e "/PORT/d" -i $WORKSPACE/docker/$ACTION.yaml
        ;;
        "default_queue")
            COMMAND="php src/artisan uniform:swoole_queue --queue=default"
            sudo sed -e "/port/d" -e "/PORT/d" -i $WORKSPACE/docker/$ACTION.yaml
        ;;
        "migrate")
            COMMAND="php src/artisan migrate"
            sudo sed -e "/port/d" -e "/PORT/d" -e "/restart/d" -i $WORKSPACE/docker/$ACTION.yaml
        ;;
        "http")
            COMMAND="php src/artisan swoole:http start"
        ;;
        *)
            echo "Error Command!"
            exit 1
        ;;
    esac

    # 更改服务名
    sudo sed -e "s!\$SERVICE_NAME!$SERVICE_NAME!g" -e "s!\$DOCKER_REPO!$DOCKER_REPO!g" -e "s!\$COMMAND!$COMMAND!g" -e "s!\$ACTION!$ACTION!g" -e "s!\$VERSION!$VERSION!g" -i $WORKSPACE/docker/$ACTION.yaml

    echo "sudo docker-compose -f $ACTION.yaml up -d" >> $WORKSPACE/docker/start.sh
    echo "sudo docker-compose -f $ACTION.yaml down" >> $WORKSPACE/docker/stop.sh
}


buildProj(){
    # 修改配置文件
    sudo cp -f $WORKSPACE/src/.env-${BUILD_TYPE} $WORKSPACE/src/.env

    echo "#!/bin/bash" > $WORKSPACE/docker/start.sh
    echo "#!/bin/bash" > $WORKSPACE/docker/stop.sh
    # 生成yaml模板文件
    for action in ${ACTIONS[@]}
    do
        createYaml $action
    done
    # 添加权限
    sudo chmod +x $WORKSPACE/src/*.sh
    sudo chmod -R 777 $WORKSPACE/src/storage
}
